import os
import subprocess
import sys
import re
import tkinter as tk
from tkinter import filedialog


def mp4_to_m3u8(input_file, output_dir, segment_time=10):
    if not os.path.exists(input_file):
        print(f"❌ 输入文件不存在: {input_file}")
        return

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    output_m3u8 = os.path.join(output_dir, "playlist.m3u8")
    segment_pattern = os.path.join(output_dir, "segment_%03d.ts")

    # 先获取视频时长
    probe_cmd = ["ffprobe", "-v", "error", "-show_entries",
                 "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", input_file]
    try:
        total_time = float(subprocess.check_output(probe_cmd).strip())
    except Exception:
        total_time = None

    command = [
        "ffmpeg",
        "-i", input_file,
        "-c:v", "libx264",
        "-c:a", "aac",
        "-f", "hls",
        "-hls_time", str(segment_time),
        "-hls_list_size", "0",
        "-hls_segment_filename", segment_pattern,
        output_m3u8
    ]

    process = subprocess.Popen(command, stderr=subprocess.PIPE, text=True)

    time_pattern = re.compile(r"time=(\d+):(\d+):(\d+\.\d+)")

    for line in process.stderr:
        match = time_pattern.search(line)
        if match and total_time:
            h, m, s = match.groups()
            seconds = int(h) * 3600 + int(m) * 60 + float(s)
            percent = min(100, seconds / total_time * 100)
            # 动态进度条显示
            bar_len = 40
            filled = int(bar_len * percent / 100)
            bar = "=" * filled + ">" + " " * (bar_len - filled)
            sys.stdout.write(f"\r[{bar}] {percent:.2f}%")
            sys.stdout.flush()

    process.wait()
    print("\n✅ 转换完成！")


if __name__ == "__main__":
    # 打开文件选择窗口
    root = tk.Tk()
    root.withdraw()  # 不显示主窗口
    input_file = filedialog.askopenfilename(
        title="选择一个 MP4 文件",
        filetypes=[("MP4 files", "*.mp4"), ("All files", "*.*")]
    )
    if not input_file:
        print("❌ 没有选择文件")
        sys.exit(0)

    # 默认输出目录：和输入文件同目录下的 output_hls
    output_dir = os.path.join(os.path.dirname(input_file), "output_hls")

    mp4_to_m3u8(input_file, output_dir, segment_time=10)
